package com.tianya.forum.controller;


import com.tianya.forum.common.AppResult;
import com.tianya.forum.common.ResultCode;
import com.tianya.forum.config.AppConfig;
import com.tianya.forum.model.Message;
import com.tianya.forum.model.User;
import com.tianya.forum.services.IMessageService;
import com.tianya.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;


@Api(tags = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;



    /**
     * 发送站内信
     *
     * @param receiveUserId 接收⽤⼾Id
     * @param content 内容
     * @return AppResult
     */
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult sned(HttpServletRequest request,
                          @ApiParam(value = "接收⽤⼾Id") @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam(value = "站内信内容") @RequestParam(value = "content") @NonNull String content){

        // 获取发送⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔
        if (user.getState() != 0) {
            // ⽇志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = "
                    + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 不能给⾃⼰发送
        if (user.getId().equals(receiveUserId)) {
            // ⽇志
            log.warn("不能给⾃⼰发送站内信. postUserId = " + user.getId() + ", receiveUserId = " + receiveUserId);
                    // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        // 查询接收⽤⼾
        User receiveUser = userService.selectById(receiveUserId);
        // ⽬标⽤⼾不存在
        if (receiveUser == null || receiveUser.getDeleteState() != 0) {
            // ⽇志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", receiveUserId = " + receiveUserId);
                    // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        // 调⽤业务层
        messageService.create(message);
        // 返回结果
        return AppResult.success();
    }


    /**
     * 查询⽤⼾的所有站内信
     *
     * @return 站内信集合
     */
    @ApiOperation("查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        // 获取当前登录⽤⼾
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 获取⽤⼾站内信
        List<Message> result = messageService.selectByReceiveUserId(user.getId());
        // 返回结果
        return AppResult.success(result);
    }



    @ApiOperation("获取未读消息个数")
    @GetMapping("//getUnreadCount")
    public AppResult getUnreadCount(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Integer result = messageService.selectUnreadCount(user.getId());
        return AppResult.success(result);
    }


    /**
     * 更新状态为已读
     *
     * @param id 站内信Id
     * @return AppResult<Message>
     */
    @ApiOperation("更新状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam(value = "站内信ID")@RequestParam(value = "id")@NonNull Long id){

        Message message = messageService.selectById(id);
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(!user.getId().equals(message.getReceiveUserId())){
            // 打印⽇志
            log.warn("查询了不属于⾃⼰的站内信：userId = " + user.getId() + ", receiveUserId = " + message.getReceiveUserId());
                    // 返回错误结果
            return AppResult.failed(ResultCode.FAILED);
        }
        // 更新为已读状态
        messageService.updateStateById(id,(byte) 1);
        return AppResult.success();
    }


    /**
     *
     * @param repliedId 要回复的站内信ID
     * @param content 内容
     * @return 成功
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                            @ApiParam("要回复的站内信Id") @RequestParam("repliedId")@NonNull Long repliedId,
                            @ApiParam("站内信的内容") @RequestParam("content")@NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给⾃⼰回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复⾃⼰的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        // 调⽤Service
        messageService.reply(repliedId, message);
        // 返回结果
        return AppResult.success();
    }

}
